/**
 * copyright (c) 2017-2023 厦门风领科技有限公司
 * https://www.fengling.cn/
 * 
 * 微信小游戏适配
 * zengbinsi
 * 2020-08-15 15:34:44
 * 2023-10-23 15:26:07
 */



window.gg = window.gg || {};

if (gg.isMiniGameWX) {
    console.log('[TS-API] ===>>>', '适配微信小游戏平台');


    gg.channel = cc.sys.os === cc.sys.OS_IOS ? gg.EChannelType.MINI_GAME_WX_IOS : gg.EChannelType.MINI_GAME_WX_AND;
    /**
     * 更新微信App
     * https: //developers.weixin.qq.com/minigame/dev/api/base/update/wx.updateWeChatApp.html
     */
    gg.updateApp = gg.updateWeChatApp;
    /** 游戏对局回放功能 */
    gg.getGameRecorderManager = gg.getGameRecorder;
    gg.exitApp = gg.exitMiniProgram;

    /** 验证小游戏新版本  */
    (function () {
        gg.__applyUpdate = false;
        gg.checkUpdateVersion = () => {
            //在首页 window['__loadResTag__'] == "Game" 或为空时可更新
            if (window['__loadResTag__'] == "UI" || window.inGameState) { return; }
            const updateManager = gg.getUpdateManager();
            if (gg.__applyUpdate) {
                if (!window.inGameState) {
                    // 应用新版本
                    gg.__applyUpdate = false;
                    window['__clearCache'] = true;
                    // 应用新版本时将本地旧版本缓存清理，进入新版本后重新下载新版本缓存
                    cc.assetManager.cacheManager.clearCache();
                    cc.sys.localStorage.setItem('__clearCache', 1);
                    updateManager.applyUpdate();
                }
                return;
            }

            // 请求完新版本信息的回调
            updateManager.onCheckForUpdate((res) => {
                gg.log('check game update:', res);
            });

            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.onUpdateReady(() => {
                gg.log('update game successd');
                // updateManager.applyUpdate();
                // 添加标记
                gg.__applyUpdate = true;

                //清理缓存
                // cc.assetManager.cacheManager.clearLRU();
            });

            // 新的版本下载失败
            updateManager.onUpdateFailed(() => {
                gg.log('update game failed');
            });
        };

        gg.checkUpdateVersion();
    })();


    /** 声明周期回调 */
    (function () {
        const sysInfo = wx.getSystemInfoSync();
        gg.sysInfo = sysInfo;
        gg.log('设备性能等级', sysInfo.benchmarkLevel);
        gg.launchOption = gg.getLaunchOptionsSync();
        gg.log('冷启动参数：', gg.launchOption);

        // 是否是分享跳出游戏
        let isShare = false;

        gg.onShow((option) => {
            gg.log('游戏唤醒参数:', option);

            gg.checkUpdateVersion();
            gg.launchOption = option || {};
            gg.systemEvent.emit('WECHAT_MINI_GAME_SHOW', gg.launchOption);
            if (option.scene === 1038 && option.referrerInfo) {
                gg.flog('支付返回:', option.referrerInfo);
                gg.systemEvent.emit(`PAY_MINI_PROGRAM_${option.referrerInfo.appId}`, option.referrerInfo.extraData);
            }
        });

        gg.onHide((res) => {
            gg.log('游戏暂停参数:', res);
            isShare = false;
            try {
                gg.systemEvent.emit('WECHAT_MINI_GAME_HIDE', res);
                if (!res || !res.mode) {
                    return;
                }
                if (res.mode === 'close') {
                    return gg.systemEvent.emit('WECHAT_MINI_GAME_CLOSE', res);
                }
                if (!res.targetPagePath) {
                    return;
                }

                // 用户去向统计
                gg.systemEvent.emit('POST_USER_GOING', JSON.parse(JSON.stringify(res)));

                // 新增点击banner判定逻辑防止微信变更mode类型  by zengbinsi 20191127
                if (res.targetPagePath.indexOf('weixinadinfo') !== -1 && res.targetPagePath.indexOf('gdt_vid') !== -1) {
                    // 点击电商banner广告
                    if (res.targetPagePath.indexOf('mp.weixin.qq.com/mp/ad_biz_info') !== -1) {
                        res.adType = '关注公众号链接';
                    } else {
                        // 包含可h5弹窗跳转APP的页面
                        res.adType = '电商链接';
                    }
                    return gg.systemEvent.emit('WECHAT_MINI_GAME_TOUCH_BANNER_AD', res);
                } else if (res.targetPagePath.indexOf('SnsAdNativeLandingPagesPreviewUI') !== -1) {
                    // 点击下载页banner广告
                    res.adType = 'APP下载页';
                    return gg.systemEvent.emit('WECHAT_MINI_GAME_TOUCH_BANNER_AD', res);
                }

                // 游戏挂起事件判定
                if (res.mode === 'hide') {
                    if (res.targetPagePath.indexOf('SnsAdNativeLandingPagesPreviewUI') !== -1) {
                        // 点击下载页banner广告
                        res.adType = 'APP下载页';
                        gg.systemEvent.emit('WECHAT_MINI_GAME_TOUCH_BANNER_AD', res);
                    } else if (res.targetPagePath.indexOf('weixinadinfo') !== -1 && res.targetPagePath.indexOf('gdt_vid') !== -1) {
                        // 点击电商banner广告
                        if (res.targetPagePath.indexOf('mp.weixin.qq.com/mp/ad_biz_info') !== -1) {
                            res.adType = '关注公众号链接';
                        } else {
                            // 包含可h5弹窗跳转APP的页面
                            res.adType = '电商链接';
                        }
                        gg.systemEvent.emit('WECHAT_MINI_GAME_TOUCH_BANNER_AD', res);
                    } else if (res.targetPagePath.indexOf('SelectConversationUI') !== -1 || res.targetPagePath.indexOf('MMUINavigationController') !== -1) {
                        // 进入好友选择列表(分享)
                        isShare = true;
                        gg.systemEvent.emit('WECHAT_MINI_GAME_EMIT_SHARE', res);
                    } else if (res.targetPagePath.indexOf('mp.weixin.qq.com/mp/wapreportwxadevlog?action=get_page&appid=wx') !== -1) {
                        // 进入意见反馈页面
                        gg.systemEvent.emit('WECHAT_MINI_GAME_FEED_BACK', res);
                    } else if (res.targetPagePath.indexOf('AppBrandProfileUI') !== -1 || res.targetPagePath.indexOf('NewWAProfileViewController') !== -1) {
                        // 进入关于小程序界面
                        gg.systemEvent.emit('WECHAT_MINI_GAME_ABOUT', res);
                    }
                } else if (res.mode === 'launchMiniProgram') {
                    if (res.targetPagePath.indexOf('weixinadinfo') !== -1 && res.targetPagePath.indexOf('gdt_vid') !== -1) {
                        // 点击小游戏banner广告
                        res.adType = '微信小游戏';
                        gg.systemEvent.emit('WECHAT_MINI_GAME_TOUCH_BANNER_AD', res);
                    } else if (res.targetPagePath.indexOf('wx') !== -1) {
                        // 卖量跳转微信小游戏
                        gg.systemEvent.emit('WECHAT_MINI_GAME_LAUNCH_MINI_GAME', res);
                    }
                } else if (res.mode === 'back') {
                    if (res.targetAction === 9 && res.targetPagePath.indexOf('wx') !== -1) {
                        // 卖量跳转微信小游戏
                        gg.systemEvent.emit('WECHAT_MINI_GAME_LAUNCH_MINI_GAME', res);
                    }
                }
            } catch (error) {
                console.error(error);
            }
        });

        gg.onMemoryWarning((res) => {
            res = res || {};
            res.benchmarkLevel = sysInfo.benchmarkLevel;
            gg.sendEvent('memory_warn', res);
            gg.warn('内存警告', res);
            gg.triggerGC();
        });

        gg.onNetworkWeakChange((res) => {
            if (!res) { return; }
            const time = Date.now();

            if (res.weakNet && time - (gg.networkWeakChangeTime || 0) > 5 * 1000) {
                gg.networkWeakChangeTime = time;
                console.log('网络不佳，请检查网络！');
            }
        });

        gg.onShareMessageToFriend((res) => {
            gg.systemEvent.emit('ON_SHARE_MESSAGE_TO_FRIEND', res);
        });
    })();


    gg.unzipFile = (data) => {
        const fsm = gg.getFileSystemManager();
        return fsm.unzip(data);
    };

    gg.showToast = (data) => {
        return wx.showToast({
            title: data.title || '',
            icon: data.icon || 'none',
            image: data.image || '',
            duration: (data.duration * 1000) || 1500,
            mask: data.mask || false,
            success: data.success || null,
            fail: data.fail || null,
            complete: data.complete || null,
        });
    };

    gg.error = (...params) => {
        return console.error(...params);
    };

    gg.payment = (data) => {
        return new Promise(async (resolve, reject) => {
            if (cc.sys.os === cc.sys.OS_IOS) {

                try {
                    data.from = '支付';
                    let res;
                    gg.flog('iOS pay_switch:', window['pay_switch']);
                    if (window['pay_switch'] === 1) {
                        res = await gg.openCustomerServiceConversation({
                            sessionFrom: gg.stringifyJSON(data),
                            showMessageCard: true,
                            sendMessageImg: 'img/payment.png',
                            success(res) {
                                gg.flog('openCustomerServiceConversation res:', res);
                                window['SHOW_PAY_LOADING'] && gg.systemEvent.emit('PAY_SHOW_LODING', data);
                            },
                            fail(err) {
                                gg.ferror('openCustomerServiceConversation err:', err);
                            },
                        });
                        res = res || {};
                        res.msg = 'payment ok';
                        data.success && data.success(res);
                        resolve(res);
                    } else {
                        gg.navigateToMiniProgram({
                            appId: data.otherMiniProgramAppId,
                            path: `pages/pay/index?order_id=${data.orderNo}&host_name=${window.APP_SERVER_HOST}`,
                            envVersion: window['__wxConfig'].envVersion,
                            success(res) {
                                gg.flog('navigateToMiniProgram res:', res);
                                let callback;
                                callback = (res) => {
                                    if (res && res.is_success) {
                                        window['SHOW_PAY_LOADING'] && gg.systemEvent.emit('PAY_SHOW_LODING', data);
                                        res = res || {};
                                        res.msg = 'payment ok';
                                        data.success && data.success(res);
                                        resolve(res);
                                    } else {
                                        const err = { msg: 'res is null.' };
                                        data.fail && data.fail(err);
                                        reject(err);
                                    }
                                    gg.systemEvent.off(`PAY_MINI_PROGRAM_${data.otherMiniProgramAppId}`, callback, window);
                                };

                                gg.systemEvent.on(`PAY_MINI_PROGRAM_${data.otherMiniProgramAppId}`, callback, window);
                            },
                            fail(err) {
                                data.fail && data.fail(err);
                                gg.ferror('navigateToMiniProgram err2:', err);
                                reject(err);
                            },
                        });
                    }
                } catch (error) {
                    data.fail && data.fail(error);
                    return reject(error);
                }
                return;
            }

            const object = {
                mode: 'game',
                env: data.env || 0,
                offerId: data.offerId || '',
                currencyType: data.currencyType || 'CNY',
                platform: data.platform || 'android',
                buyQuantity: data.buyQuantity,
                zoneId: `${data.zoneId}` || 1,
                success: (res) => {
                    data.success && data.success(res);
                    resolve(res);
                },
                fail: (err) => {
                    data.fail && data.fail(err);
                    reject(err);
                },
                complete: (res) => {
                    data.complete && data.complete(res);
                },
            };

            gg.requestMidasPayment(object);
        });
    };

    gg.openCustomerServiceConversation = (data) => {
        return new Promise((resolve, reject) => {
            data.sendMessageTitle = data.sendMessageTitle || gg.sendMessageTitle;
            data.sendMessageImg = data.sendMessageImg || gg.sendMessageImg;

            wx.openCustomerServiceConversation({
                sessionFrom: data.sessionFrom,
                showMessageCard: data.showMessageCard,
                // sendMessageTitle: data.sendMessageTitle,
                sendMessagePath: data.sendMessagePath,
                sendMessageImg: data.sendMessageImg,
                success: (res) => {
                    gg.flog('openCustomerServiceConversation succ:', res);
                    data.success && data.success(res);
                    resolve(res);
                },
                fail: (err) => {
                    gg.flog('openCustomerServiceConversation fail:', err);
                    data.fail && data.fail(err);
                    reject(err);
                },
            });
        });
    };

    gg.getAppId = () => {
        try {
            const accountInfo = gg.getAccountInfoSync();
            if (accountInfo.miniProgram && window.AppConfig) {
                window.AppConfig.APP_ID = accountInfo.miniProgram.appId;
            }
            return accountInfo.miniProgram.appId;
        } catch (error) {
            return window.AppConfig ? window.AppConfig.APP_ID : undefined;
        }
    };

    gg.shareAppMessage = (data) => {
        return new Promise((resolve, reject) => {
            let callback, callShareTime = Date.now();
            callback = (res) => {
                gg.systemEvent.off('WECHAT_MINI_GAME_SHOW', callback, gg);
                gg.systemEvent.emit('HOME_ICON_RED_TIP');
                const time = Date.now() - callShareTime;
                gg.log('小游戏唤醒', isShare, time, res);
                if (!isShare) {
                    const err = {
                        errMsg: 'isShare is false.',
                        errCode: -1,
                        time
                    };
                    data && data.fail && data.fail(err);
                    return reject(err);
                }
                let randomNum = Math.random();
                // 后台控制分享成功的时长 以及 分享失败概率
                if ((time < (window['validShareTime'] || 3000)) || (randomNum <= (window['shareFailRatio'] || 0))) {
                    gg.log('小游戏唤醒时间过短或者过长：', time, window['validShareTime']);
                    gg.log('当前分享失败概率为：', randomNum, window['shareFailRatio']);
                    const err = {
                        errMsg: '小游戏唤醒时间过短或者过长。',
                        errCode: -1,
                        time
                    };
                    data && data.fail && data.fail(err);
                    return reject(err);
                }

                gg.log('分享成功', data);
                data = {
                    msg: 'share successed.',
                    code: 0,
                    ...data
                };
                data && data.success && data.success(data);
                resolve(data);
            };
            gg.systemEvent.on('WECHAT_MINI_GAME_SHOW', callback, gg);

            wx.shareAppMessage(data);
        });
    };

    try {
        if (gg.getRealtimeLogManager) {
            // gg.logger = gg.getLogManager({level: 1});
            gg.logger = gg.getRealtimeLogManager();
        }

        if (window['__wxConfig'] && window['__wxConfig'].envVersion === 'release') {
            // gg.logger = false;
            if (gg.logger) {
                console.log = gg.logger.log || gg.logger.info;
                console.warn = gg.logger.warn;
                console.error = gg.logger.error;
                console.debug = gg.logger.debug || gg.logger.info;
                console.info = gg.logger.info;

                gg.log = gg.logger.log || gg.logger.info;
                gg.warn = gg.logger.warn;
                gg.error = gg.logger.error;
                gg.debug = gg.logger.debug || gg.logger.info;
                gg.info = gg.logger.info;
            } else {
                console.log = () => { };
                console.warn = () => { };
                console.debug = () => { };
                console.info = () => { };
                console.error = () => { };

                gg.log = () => { };
                gg.warn = () => { };
                gg.debug = () => { };
                gg.info = () => { };
                gg.error = () => { };
            }
        } else if (window['__wxConfig'] && window['__wxConfig'].envVersion === 'trial') {
            if (gg.logger) {
                const gg_log = console.log;
                const gg_warn = console.warn;
                const gg_error = console.error;
                const gg_debug = console.debug;
                const gg_info = console.info;

                console.log = (...params) => {
                    gg.logger.info(...params);
                    return gg_log(...params);
                };
                console.warn = (...params) => {
                    gg.logger.warn(...params);
                    return gg_warn(...params);
                };
                console.error = (...params) => {
                    gg.logger.error(...params);
                    return gg_error(...params);
                };
                console.debug = (...params) => {
                    gg.logger.info(...params);
                    return gg_debug(...params);
                };
                console.info = (...params) => {
                    gg.logger.info(...params);
                    return gg_info(...params);
                };

                gg.log = (...params) => {
                    gg.logger.info(...params);
                    return gg_log(...params);
                };
                gg.warn = (...params) => {
                    gg.logger.warn(...params);
                    return gg_warn(...params);
                };
                gg.error = (...params) => {
                    gg.logger.error(...params);
                    return gg_error(...params);
                };
                gg.debug = (...params) => {
                    gg.logger.info(...params);
                    return gg_debug(...params);
                };
                gg.info = (...params) => {
                    gg.logger.info(...params);
                    return gg_info(...params);
                };
            }
        }
    } catch (error) {

    }

    gg.onReportUserBehaviorBranchAnalytics = (data) => {
        gg.reportUserBehaviorBranchAnalytics({
            branchId: data.branchId,
            eventType: data.eventType // 1：曝光； 2：点击
        });
    };
}